import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Divider, Button, Table, Space, Modal, message, Collapse, Popover, Checkbox, Input } from 'antd';
import axios from 'axios';

const { Panel } = Collapse;

const RoleView = () => {
  const [roles, setRoles] = useState([]);
  const [allPermissions, setAllPermissions] = useState([]);
  const [rolePermissions, setRolePermissions] = useState({});
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedRole, setSelectedRole] = useState(null);
  const [editingRoleId, setEditingRoleId] = useState('');
  const [editingRoleName, setEditingRoleName] = useState('');
  const navigate = useNavigate();

  useEffect(() => {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const token = currentUser?.token;
    if (token) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
      console.log('设置 Authorization 头:', `Bearer ${token}`);
    } else {
      console.error('未在 currentUser 中找到 token');
    }
    fetchPermissions();
    fetchRoles();
  }, []);

  // 获取所有权限信息
  const fetchPermissions = async () => {
    // 在浏览器控制台输入以下代码检查 token
    console.log('Authorization:', axios.defaults.headers.common['Authorization']);

    try {
      const response = await axios.get(`http://localhost:8080/api/roles/permissions`);

      // 检查 success 字段以确认请求是否成功
      if (response.data.success) {
        setAllPermissions(response.data.data); // 从 data 字段中获取权限信息
        console.log('获取权限信息成功！');
        console.log('权限信息:', response.data.data);
      } else {
        // 如果请求不成功，使用返回的消息提示错误
        message.error(`获取权限信息失败：${response.data.message}`);
      }
    } catch (error) {
      console.error('获取权限信息失败:', error);
      message.error('获取权限信息失败，请稍后再试！');
    }
  };

  // 获取所有角色以及其权限信息
  const fetchRoles = async () => {
    try {
      const response = await axios.get(`http://localhost:8080/api/roles/get-all-roles-with-permissions`);
      if (response.status === 200) {
        setRoles(response.data.data);
        console.log('获取角色信息成功！');

        // 构建 rolePermissions 对象
        const rolePermissionsMap = {};
        response.data.data.forEach(role => {
          rolePermissionsMap[role.roleId] = role.permissions.map(p => p.permissionId);
        });
        setRolePermissions(rolePermissionsMap);
      } else {
        message.error('获取角色信息失败，请稍后再试！');
      }
    } catch (error) {
      console.error('获取角色信息失败:', error);
      message.error('获取角色信息失败，请稍后再试！');
    }
  };

  const handlePermissionChange = async (roleId, permissionId, isChecked) => {
    try {
      let response;

      if (isChecked) {
        // 添加权限
        response = await axios.post(`http://localhost:8080/api/roles/${roleId}/permissions`, { permissionId });
      } else {
        // 移除权限
        response = await axios.delete(`http://localhost:8080/api/roles/${roleId}/permissions/${permissionId}`);
      }

      const data = response.data;
      if (response.status === 200 && data.code === 200) {
        message.success('权限更新成功！');
        fetchRoles(); // 刷新角色数据

        // 更新本地状态
        const updatedRolePermissions = { ...rolePermissions };
        if (isChecked) {
          updatedRolePermissions[roleId].push(permissionId);
        } else {
          updatedRolePermissions[roleId] = updatedRolePermissions[roleId].filter(id => id !== permissionId);
        }
        setRolePermissions(updatedRolePermissions);
      } else {
        message.error(data.message || '更新权限失败，请稍后再试！');
      }
    } catch (error) {
      console.error('更新权限失败:', error);
      message.error(error.response?.data?.message || '更新权限失败，请稍后再试！');
    }
  };

  const showModal = (role) => {
    setSelectedRole(role);
    setEditingRoleId('');
    setEditingRoleName('');
    setIsModalVisible(true);
  };

  const handleUpdateRoleName = async () => {
    // 验证新角色名是否为空或者与原角色名相同
    if (!editingRoleName.trim()) {
      message.warning('角色名不能为空！');
      return;
    }

    if (editingRoleName.trim() === selectedRole.roleName) {
      message.info('新角色名不能与原角色名相同！');
      return;
    }

    try {
      const response = await axios.put(`http://localhost:8080/api/roles/${selectedRole.roleId}`, {
        roleName: editingRoleName.trim()
      });

      const data = response.data;
      if (response.status === 200 && data.code === 200) {
        message.success('角色名修改成功！');
        fetchRoles(); // 刷新角色数据
        setIsModalVisible(false); // 成功后关闭模态框
      } else {
        message.error(data.message || '角色信息更新失败，请稍后再试！');
      }
    } catch (error) {
      console.error('角色信息更新失败:', error);
      message.error(error.response?.data?.message || '角色信息更新失败，请稍后再试！');
    }
  };

  const cancelUpdateRoleName = () => {
    setIsModalVisible(false);
  };

  // 删除角色
  const handleDeleteRole = async (roleId) => {
    try {
      const response = await axios.delete(`http://localhost:8080/api/roles/${roleId}`);

      const data = response.data;
      if (response.status === 200 && data.code === 200) {
        message.success('角色删除成功！');
        fetchRoles(); // 刷新角色数据
      } else {
        message.error(data.message || `返回值: ${response.status}`);
        console.error(`返回值: ${response.status}`);
      }
    } catch (error) {
      console.error('角色删除失败:', error);
      message.error('角色删除失败，请稍后再试！');
      if (error.response) {
        // 处理后端返回的错误信息
        message.error(error.response.data.message || '角色删除失败，请稍后再试！');
      } else {
        console.error('角色删除失败:', error);
      }
    }
  };

  const columns = [
    {
      title: '角色ID',
      dataIndex: 'roleId',
      key: 'roleId'
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName'
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
          <Space size="middle">
            <Button type="link" onClick={() => showModal(record)}>编辑</Button>
            <Popover
                content={
                  <div>
                    {allPermissions.map(permission => (
                        <div key={permission.permissionId} style={{ display: 'flex', alignItems: 'center' }}>
                          <Checkbox
                              checked={rolePermissions[record.roleId]?.includes(permission.permissionId)}
                              onChange={(e) => handlePermissionChange(record.roleId, permission.permissionId, e.target.checked)}
                          />
                          <span style={{ marginLeft: 8 }}>{permission.permissionName}</span>
                        </div>
                    ))}
                  </div>
                }
                title="权限列表"
                trigger="click"
            >
              <Button type="link">修改权限</Button>
            </Popover>
            <Button type="link" onClick={() => handleDeleteRole(record.roleId)}>删除</Button>
          </Space>
      )
    }
  ];

  return (
      <div>
        <div >
          <Button type="default" style={{ marginLeft: 8, width: 100, backgroundColor: "#1c84c6",color: '#fff'}} onClick={() => navigate('/admin/role/create')}>新增</Button>
        </div>
        <Divider />
        <Table
            dataSource={roles}
            columns={columns}
            rowKey="roleId"
            pagination={false}
            bordered
        />
        <Modal
            title={`编辑角色: ${selectedRole?.roleName}`}
            visible={isModalVisible}
            onOk={handleUpdateRoleName}
            onCancel={cancelUpdateRoleName}
            footer={[
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <Button key="cancel" onClick={cancelUpdateRoleName} style={{ width: '100px' }}>
                  取消
                </Button>
                <Button key="submit" type="primary" onClick={handleUpdateRoleName} style={{ width: '100px', marginLeft: '8px' }}>
                  保存
                </Button>
              </div>
            ]}
            centered
            style={{ alignItems: 'center' }}
        >
          <div style={{ padding: '16px' }}>
            <div style={{ marginBottom: '16px', display: 'flex', alignItems: 'center' }}>
              <label style={{ width: '80px', marginRight: '8px' }}>角色ID:</label>
              <span>{selectedRole?.roleId}</span> {/* 显示只读的角色ID */}
            </div>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <label style={{ width: '80px', marginRight: '8px' }}>角色名称:</label>
              <Input
                  value={editingRoleName}
                  onChange={(e) => setEditingRoleName(e.target.value)}
                  placeholder={selectedRole?.roleName}
                  style={{ flex: 1, maxWidth: '300px' }}
              />
            </div>
          </div>
        </Modal>
      </div>
  );
};

export default RoleView;